﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;

namespace _21._1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void buttonLoop_Click(object sender, RoutedEventArgs e)
        {
            XmlDocument document = new XmlDocument();
            document.Load(@"f:\WORK2024\PRO\C#\C#入门经典(第八版）\第21章\XML\GhostStoris.xml");
            textBlockResults.Text = FormatText(document.DocumentElement as XmlNode, "", "");
        }

        private string FormatText(XmlNode xmlNode, string v1, string v2)
        {
            if (xmlNode is XmlText)
            {
                v1 += xmlNode.Value;
                return v1;
            }

            if (string.IsNullOrEmpty(v2))
                v2 = "";
            else
                v1 += "\r\n" + v2;

            if (xmlNode is XmlComment)
            {
                v1 += xmlNode.OuterXml;
                return v1;
            }
            v1 += "<" + xmlNode.Name;
            if (xmlNode.Attributes.Count > 0)
            {
                Addattributes(xmlNode, ref v1);
            }
            if (xmlNode.HasChildNodes)
            {
                v1 += ">";
                foreach (XmlNode CHILD in xmlNode.ChildNodes)
                {
                    v1 = FormatText(CHILD, v1, v2 + " ");
                }
                if (xmlNode.ChildNodes.Count == 1 && (xmlNode.FirstChild is XmlText || xmlNode.FirstChild is XmlComment))
                    v1 += "</" + xmlNode.Name + ">";
                else
                    v1 += "\r\n" + v2 + "</" + xmlNode.Name + ">";
            }
            else
                v1 += "/>";
            return v1;
        }
        private void Addattributes(XmlNode xmlNode, ref string v1)
        {
            foreach (XmlAttribute a in xmlNode.Attributes)
            {
                v1 += " " + a.Name + "='" + a.Value + "'";
            }
            
        }

        
    }
}
